#include "myclient.h"
#include "mytask.h"
#include <QThreadPool>

MyClient::MyClient(QObject *parent)
    : QObject(parent)
{

}

void MyClient::setSocketDescriptor(qintptr id)
{
    socket = new QTcpSocket(this);

    connect(socket, SIGNAL(connected()), this, SLOT(connected()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnect()));

    socket->setSocketDescriptor(id);

    qDebug() << "Client connected at " << id;
}

void MyClient::readyRead()
{
    qDebug() << "MyClient::readyRead()";
    QByteArray data = socket->readAll();
    qDebug() << data;

    bool ok;
    int argument = data.toInt(&ok);
    if (!ok){
        qDebug() << "Could not convert received data.";
        qDebug() << data.size();
    }

    MyTask *task = new MyTask(argument);
    task->setAutoDelete(true);

    connect(task, SIGNAL(Result(int)),
            this, SLOT(TaskResult(int)),Qt::QueuedConnection);

    qDebug() << "starting a task using a thread from QThreadPool";

    QThreadPool::globalInstance()->start(task);
}

void MyClient::disconnect()
{
    qDebug() << "Client disconnected.";
}

void MyClient::connected()
{
    qDebug() << "Client Connected.";
}

void MyClient::TaskResult(int Number)
{
    QByteArray buffer;
    buffer.append("Task result = ");
    buffer.append(QString::number(Number));

    socket->write(buffer);
}




